/**
 *@description:上海银行信用卡，抓取、解析 流程包装处理
 *@author: LiTao
 *@date:2018/8/24
 */


/*********************************封装不同业务数据的抓取、解析****************************************/
var sh_credit_handle= {

    /**
     * @description:上海信用卡抓取、解析主流程
     */
     credit_crawl_main:function(){

        //抓取用户基础信息
        sh_credit_handle.crawlBasicUserInfo();

        //解析用户基础信息
        sh_credit_handle.parseBaseUserInfo();

        //抓取已出账单
        sh_credit_handle.crawlDONE();

        //解析已出账单
        sh_credit_handle.parseDONE();
    },



/***************************具体的抓取\解析方法***************************/
    /**
     * 抓取更多用户基础信息
     */
    crawlBasicUserInfo:function(){

        //从上下文获取信用卡集合
        var cardInfoList=context.get(keys.CRED_CARD_LIST);

        //定义卡序号
        var creditCardNum=1;

        //存放每张卡的信息页面
        var cardMap=new HashMap();

        //遍历每张卡
        for(var i=0;i<cardInfoList.size();i++){
            var  basic_info= ajax_get(sh_credit_urls.BASIC_INFO_URL);
            storeDataToFile(context,basic_info, (creditCardNum++)+"_basic_info.html");

            //获取卡信息map
            var creditCardMap=cardInfoList.get(i);
            //获取全卡号
            var fullCardNum=creditCardMap.get(keys_sh.FULL_CARD_NUM);
            //根据卡号，存放页面
            cardMap.put(fullCardNum,basic_info);
        }

        //添加到上下文
        context.put(keys.BASE_MAP,cardMap);
    },

    /**
     * @scription:解析用户基础信息
     */
    parseBaseUserInfo: function () {
        try {
            //从上下文获取信用卡集合
            var cardInfoList = context.get(keys.CRED_CARD_LIST);

            //从上下文，获取信用卡数据对象集合
            var data_list = context.get(keys.CREDIT_DATA);

            //从上下文获取基础信息map
            var basicInfoMap = context.get(keys.BASE_MAP);

            //遍历每张卡
            for (var i = 0; i < cardInfoList.size(); i++) {
                //获取信用卡
                var creditCardAllData = data_list.get(i);
                //获取卡信息map
                var creditCardMap=cardInfoList.get(i);
                var full_card_num = creditCardMap.get(keys_sh.FULL_CARD_NUM);


                creditCardAllData.setFullCardNum(full_card_num);
                creditCardAllData.setCardNum(full_card_num.substring(full_card_num.length - 4,full_card_num.length));

                creditCardAllData.setNameOnCard(context.get(keys.USER_NAME));
                creditCardAllData.setOpenBank(creditCardMap.get(keys_sh.CRED_OPEN_BANK));

                //根据卡号获取基础信息页面
                var basicHtml = basicInfoMap.get(full_card_num);
                //解析
                parseBasicHtml(creditCardAllData, basicHtml)
            }
        } catch (e) {
            logger.error("解析用户基础信息异常,行【"+e.lineNumber+"】异常信息【"+e.message+"】");
            statCaughtExceptionByJS(context,e);
        }
        return;


        /**
         * 解析基础信息页面
         * @param creditCardAllData
         * @param basicInfoHtml
         */
        function parseBasicHtml(creditCardAllData,basicInfoHtml) {
            var doc = Jsoup.parse(basicInfoHtml);
            var html = doc.select(".errors_def").html();
            if (html.contains("未持有我行信用卡")) {
                logger.info("无信用卡基础信息，停止抓取信用卡");
                return;
            }

            //信用卡额度
            var credit_limit= doc.select("tr.trValue:nth-child(3) > td:nth-child(4)").get(0).text();
            //可用额度
            var balance=doc.select("tr.trValue:nth-child(4) > td:nth-child(4)").get(0).text();
            //现金可用额度
            var cashBalance=doc.select("tr.trValue:nth-child(5) > td:nth-child(4)").get(0).text();

            //账单到期还款日
            payMentDate=doc.select("tr.trValue:nth-child(12) > td:nth-child(4)").get(0).text();
            //填充数据
            var cash_balance=CreditResultUtil.StringToBigDecimal(cashBalance);
            creditCardAllData.setCardId(UUID.randomUUID().toString());
            creditCardAllData.setBalance(CreditResultUtil.StringToBigDecimal(balance));
            creditCardAllData.setCashBalance(cash_balance);
            creditCardAllData.setCreditLimit(CreditResultUtil.StringToBigDecimal(credit_limit));
        }
    },

    /**
     * 抓取已出账单
     */
    crawlDONE:function(){
        //从上下文获取信用卡集合
        var cardInfoList=context.get(keys.CRED_CARD_LIST);

        //定义卡序号
        var creditCardNum=1;

        //存放每张卡的已出账单
        var doneMap=new HashMap();

        //遍历每张卡
        for(var i=0;i<cardInfoList.size();i++){

            var queryBillHtml = ajax_get(sh_credit_urls.QUERY_BILL_URL);
            storeDataToFile(context,queryBillHtml,(creditCardNum+i)+"_queryMonthHtml.txt");

            //精确到月的账单月集合
            var monthArray =null;
            //精确到天的账单日集合
            var dateArray=null;
            try {
                //精确到天的账单日集合
                var queryDates = getGroup0("var dueDates= *(.*)",queryBillHtml).replaceAll("var dueDates=|;", "");//['','','2017-08-06']
                //精确到月的账单月集合
                var queryMonths=getGroup0("var dataX=*(.*)",queryBillHtml).replaceAll("var dataX=|;", "");//['2016-10', '2016-11', '2016-12', ]
                monthArray=JSON.parse(queryMonths);
                dateArray=JSON.parse(queryDates);

            } catch (e) {
                logger.error("上海信用卡解析已出账单日期集合异常,行【"+e.lineNumber+"】异常信息【"+e.message+"】");
            }

            //解析日期数据,完成对monthArray,dateArray的赋值
            // parseDateData(queryBillHtml,monthArray,dateArray);

            //存放已出账单的Map
            var doneBillMap=new LinkedHashMap();

            //logger.info("monthArray=="+monthArray.())
            //遍历所有月份
            for(var j=0;j<monthArray.size();j++) {
                var date = dateArray.get(j);
                var month=monthArray.get(j)

                logger.info("上海信用卡开始抓取{}月的账单",month);
                var param=new HashMap();
                param.put("BillMonth",month.replaceAll("-", ""));
                param.put("dueDate", date.replaceAll("-", ""));


                var billMonthHtml = ajax_post(sh_credit_urls.DONE_BILL_URL, param);
                storeDataToFile(context,billMonthHtml,(creditCardNum+i)+"_"+month+"_bill.html");

                //依据月份，添加已出账单
                doneBillMap.put(month,billMonthHtml);
            }

            //卡信息map
            var creditCardMap=cardInfoList.get(i);
            //卡号
            var full_card_num = creditCardMap.get(keys_sh.FULL_CARD_NUM);

            //根据卡号，存放每张卡的所有已出账单
            doneMap.put(full_card_num,doneBillMap);
        }

        //添加到上下文
        context.put(keys.DONE_MAP,doneMap);
        return;


        /**
         * 解析日期数据
         * @param queryBillHtml
         */
        function parseDateData(queryBillHtml,monthArray,dateArray){
            try {
                //精确到天的账单日集合
                var queryDates = getGroup0("var dueDates= *(.*)",queryBillHtml).replaceAll("var dueDates=|;", "");//['','','2017-08-06']
                //精确到月的账单月集合
                var queryMonths=getGroup0("var dataX=*(.*)",queryBillHtml).replaceAll("var dataX=|;", "");//['2016-10', '2016-11', '2016-12', ]
                monthArray=JSON.parse(queryMonths);
                dateArray=JSON.parse(queryDates);

                logger.info("queryDates=="+queryDates.size())
                logger.info("queryMonths=="+queryMonths.size())
            } catch (e) {
                logger.error("上海信用卡解析已出账单日期集合异常,行【"+e.lineNumber+"】异常信息【"+e.message+"】");
            }
        }
    },

    /**
     * 解析已出账单详情
     */
    parseDONE:function() {
        try {
            //从上下文获取信用卡集合
            var cardInfoList = context.get(keys.CRED_CARD_LIST);

            //从上下文获取信用卡数据对象集合
            var data_list = context.get(keys.CREDIT_DATA);

            //从上下文获取已出账单map
            var doneMap = context.get(keys.DONE_MAP);

            //遍历每张卡
            for (var i = 0; i < cardInfoList.size(); i++) {

                //获取数据对象
                var creditCardAllData = data_list.get(i);

                //获取每个卡对应的月账单集合
                var billList = creditCardAllData.getBills();

                //舍弃掉creditCardAllData初始时创建的对象内容,因其中有用的数据很少
                 billList.clear();

                //卡信息map
                var creditCardMap = cardInfoList.get(i);

                //卡号
                var full_card_num = creditCardMap.get(keys_sh.FULL_CARD_NUM);

                //依据卡号，获取每张卡的已出账单页
                var doneBillMap = doneMap.get(full_card_num);

                //遍历所有月份
                for each(entry in doneBillMap.entrySet()){

                    //获取月份时间
                    var billMonth = entry.getKey();
                    //获取已出账单页
                    var billMonthHtml = entry.getValue();
                    //解析
                    parseDoneBillMain(billMonthHtml,creditCardAllData,billMonth);
                }
            }
        } catch(e) {
            logger.error("上海信用卡已出账单解析异常,行【"+e.lineNumber+"】异常信息【"+e.message+"】");
            //statCaughtExceptionByJS(context,e);
        }
    },
    /**
     * 抓取未出账单
     */
    crawlUONE:function(){
        //从上下文获取信用卡用户信息集合
        var cardInfoList=context.get(keys.CRED_CARD_LIST);

        //定义详情页序号
        var billDetailNum=1;

        //存放所有未出账单页
        var undoBillList=new ArrayList();

        //存放未出账单的map
        var undoMap=new HashMap();

        //遍历每张卡
        for(var i=0;i<cardInfoList.size();i++) {
            //获取未出账单查询请求参数
            var undoQueryParam = buildUndoQueryParam();

            //获取未出账单详情页 首页
            var undoBillHtml = ajax_post(sh_credit_urls.UNDO_BILL_URL, undoQueryParam);
            storeDataToFile(context, undoBillHtml, (i+1)+"undone_shopping_sheets_"+billDetailNum + ".html");

            //添加未出账单详情页 首页
            undoBillList.add(undoBillHtml);

            //进行翻页请求，获取全部未出账单
            fanyeUndoBill(undoBillHtml, undoBillList, billDetailNum);

            //卡信息map
            var creditCardMap=cardInfoList.get(i);
            //卡号
            var fullCardNum = creditCardMap.get(keys_sh.FULL_CARD_NUM);

            //依据卡号，添加 每张卡的所有未出账单页
            undoMap.put(fullCardNum,undoBillList);
        }
        //添加到上下文
        context.put(keys.UNDO_MAP,undoMap);
        return;

        //构建未出账单，查询请求参数
        function buildUndoQueryParam(){
            var undoneBillOne = ajax_get(sh_credit_urls.UNDO_QUERY_URL);
            storeDataToFile(context,undoneBillOne, "queryUndoneBill.txt");
            var doc = Jsoup.parse(undoneBillOne);

            //存放查询参数
            var map=new LinkedHashMap();

            var elements = doc.select("body>input");

            var element="";
            for each(element in elements) {
                var name = element.attr("name");
                var value=element.attr("value");
                map.put(name, value);
            }
            map.put("CRFlag", "Cs");
            map.put("Code", "CNY");//暂定为人民币消费
            return map;
        }

        //进行翻页请求，获取全部未出账单
        function fanyeUndoBill(undoBillHtml,undoBillList,billDetailNum){
            var doc = Jsoup.parse(undoBillHtml);
            var pageNumStr = doc.select(".pagesbutton").html();
            pageNumStr=pageNumStr.split("共")[1];
            pageNumStr=pageNumStr.substring(0, 1);
            var pageNum = Integer.parseInt(pageNumStr);
            var elements= doc.select("body>input");
            //存放请求参数
            var map=new HashMap();
            var element="";
            for each(element in elements) {
                var name = element.attr("name");
                var value=element.attr("value");
                map.put(name, value);
            }
            //翻页请求，获取未出账单详情页
            for(var i=1;i<pageNum;i++){
                var currentIndex=10;
                currentIndex=currentIndex*i;
                map.put("currentIndex",Integer.toString(currentIndex));
                var html = ajax_post(url, map);
                storeDataToFile(context,html, (i+1)+"undone_shopping_sheets_"+(billDetailNum++)+".html");

                //添加未出账单详情页的 每一页
                undoBillList.add(undoBillHtml);
            }
        }
    },
    /**
     * 解析未出账单
     */
    parseUNDO:function(){
        try { //从上下文，获取未出账单map
            var undoMap = context.get(keys.UNDO_MAP);

            //从上下文获取信用卡用户信息集合
            var cardInfoList = context.get(keys.CRED_CARD_LIST);

            //从上下文，获取数据对象集合
            var data_list = context.get(keys.CREDIT_DATA);

            //遍历每张卡
            for (var i = 0; i < cardInfoList.size(); i++) {
                //卡信息map
                var creditCardMap = cardInfoList.get(i);
                //卡号
                var fullCardNum = creditCardMap.get(keys_sh.FULL_CARD_NUM);

                //依据卡号，获取每张卡的未出账单集合
                var undoBillList = undoMap.get(fullCardNum);

                //获取每个卡对应的数据对象
                var creditCardAllData = data_list.get(i);

                //获取每个卡的账单集合
                var billList = creditCardAllData.getBills();

                //遍历未出账单
                for (var j = 0; j < undoBillList.size(); j++) {

                    //获取未出账单详情页
                    var undoBillHtml = undoBillList.get(j);
                    //解析
                    parseUndoBillMain(creditCardAllData, undoBillHtml, billList);
                }
            }
        } catch (e) {
            logger.error("上海信用卡未出账单解析异常,行【"+e.lineNumber+"】异常信息【"+e.message+"】");
            statCaughtExceptionByJS(context,e);
        }
    }

}

/**
 * 解析未出账单详情主方法
 * @param creditCardAllData
 * @param undoBillHtml
 * @param billList
 */
function parseUndoBillMain(creditCardAllData,undoBillHtml,billList){

    //账单实例
    var billAllData =new BillAllData();

    //解析未出账单,表头数据
    parseUndoBaseData(creditCardAllData,billAllData);

    //解析未出账单,购物账单明细
    parseUndoShoppingSheets(billAllData,undoBillHtml);
}


/**
 * 解析未出账单,表头数据
 */
function parseUndoBaseData(creditCardAllData,billAllData){

    billAllData.setBankName("上海银行");
    // billAllData.setBillId(UUID.randomUUID().toString());
    // billAllData.setBillType("UNDONE");
    var billMonthAndDate = getUndoneBillMonthAndDate();
    billAllData.setBillMonth(billMonthAndDate[0]);
    billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(billMonthAndDate[1]));
    billAllData.setPaymentDueDate(null);//从账户信息页面取出
    billAllData.setCreditLimit(null);
    billAllData.setCashLimit(null);

    var usd_credit_limit=usdCreditLimitInfoMap.get(basicInfoUsdCreditLimit);
    billAllData.setUsdCashLimit(null);
    billAllData.setUsdCreditLimit(CreditResultUtil.StringToBigDecimal(usd_credit_limit));

    billAllData.setInterest(null);
    billAllData.setUsdInterest(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setUsdNewBalance(null);
    billAllData.setUsdNewCharges(null);

    var bills = creditCardAllData.getBills();
    if (bills.size()>0) {
        billAllData.setLastBalance(bills.get(bills.size()-1).getNewBalance());
        billAllData.setNewBalance(bills.get(bills.size()-1).getNewBalance());
    }

    if (bills.size()==0) {
        billAllData.setNewBalance(null);
        billAllData.setLastBalance(null);
    }
}

/**
 * 解析未出账单,购物账单明细
 */
function parseUndoShoppingSheets(billAllData,undoBillHtml){
    var document = Jsoup.parse(undoBillHtml);
    var undoneFlag=null;
    try {
        undoneFlag= document.select( "#listTable > tbody:nth-child(2) > tr:nth-child(2) > td:nth-child(1)").get(0).text();
    }catch (e) {
        logger.error("未出账单页面解析失败，停止抓取",e);
        return;
    }
    if (undoneFlag.equals("查询无记录")) {
        logger.info("未出账单没有记录，停止抓取");
        return;
    }

    var currecy="CNY";
    parseUndoneInfo(billAllData, undoBillHtml,currecy);
}



//定义请求链接
var sh_credit_urls={
    //用户基础信息
    BASIC_INFO_URL:"https://ebanks.bankofshanghai.com/pweb/CreditAcctInfoQry.do?_navigator=pcreditcard.cardactqry.CreditAcctInfoQry",
    //已出账单查询页
    QUERY_BILL_URL:"https://ebanks.bankofshanghai.com/pweb/CreditBillOutQueryPre.do?_navigator=pcreditcard.creditpaymgmt.BillOutQry",
    //已出账单详情
    DONE_BILL_URL:"https://ebanks.bankofshanghai.com/pweb/CreditBillOutQuery.do",
    //未出账单查询页
    UNDO_QUERY_URL:"https://ebanks.bankofshanghai.com/pweb/CreditBillInQueryPre.do?_navigator=pcreditcard.creditpaymgmt.BillInQry",
    //未出账单详情
    UNDO_BILL_URL:"https://ebanks.bankofshanghai.com/pweb/CreditBillInQuery.do"
}


/**
 * 解析已出账单详情主方法
 * @param doneBillHtml
 * @param creditCardAllData
 * @param billMonth
 */
function parseDoneBillMain(doneBillHtml,creditCardAllData,billMonth){

    var doc = Jsoup.parse(doneBillHtml);

    //账单实例
    var billAllData=new BillAllData();

    //解析已出账单表头数据(人民币)
    parseDoneBillBaseData(doc,billAllData,billMonth);

    //解析已出账单表头数据(美元)
    parseDollarBaseData(doc,billAllData);

    //存放分期手续费
    var handFeeList=new LinkedList();

    //解析已出账单,分期明细，并获取分期手续信息
    try {
        var installmentList = parseDoneInstallments(doc, handFeeList);

        if (installmentList.size() != 0) {
            //计算分期手续费
            parseInstallmentAndHandFee(installmentList, handFeeList);
        }
    } catch (e) {
        logger.error("上海信用卡已出账单分期明细解析异常,行【"+e.lineNumber+"】异常信息【"+e.message+"】");
    }


    //解析已出账单,购物账单明细
    var shoppingSheets=parseDoneShoppingSheets(doc);

    //填充数据
    billAllData.setShoppingSheets(shoppingSheets);
    billAllData.setInstallments(installmentList);

    //添加账单实例
    creditCardAllData.getBills().add(billAllData);

    //解析已出账单的美元信息
    parseUsdDoneBill(doc,billAllData);
}

/**
 * 解析已出账单表头数据(人民币)
 */
function parseDoneBillBaseData(doc,billAllData,billMonth){
    //上期账单金额
    var last_balance=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(3) > span:nth-child(1)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
    //本期新增款额
    var new_charges=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(4)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
    //本期账单金额
    var new_balance=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(7)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
    //最低还款额
    var min_payment=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(8)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
    //上期还款金额
    var last_payment=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(5)").get(0).text();//上期还款金额，如果没有取当前的还款金额

    var monthInfoAndCreditLimit=doc.select("div.szmx:nth-child(1)").html();
    var monthInfoCreditLimits = monthInfoAndCreditLimit.split("信用卡额度：RMB");
    var creditLimit="";
    if (monthInfoCreditLimits.length>0) {
        //信用卡额度
        creditLimit=monthInfoCreditLimits[1].trim().replaceAll(",", "").replaceAll(",", "").replaceAll("&nbsp; ", "");
    }
    var begin=monthInfoAndCreditLimit.indexOf("到期还款日：");
    var endIndex=monthInfoAndCreditLimit.indexOf("信用卡额度：RMB");
    //还款日
    var paymentDueDate = monthInfoAndCreditLimit.substring(begin, endIndex).trim().replaceAll("&nbsp;", "").replaceAll("到期还款日：", "").replaceAll("\\s", "");;

    //填充数据
    billAllData.setBillId(UUID.randomUUID().toString());
    billAllData.setBankName("上海银行");
    //账单日  通过抓取的页面，判断出中信账单日为每月8号
    billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(billMonth+"-"+"08"));
    //还款日
    billAllData.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(paymentDueDate));
    billAllData.setBillMonth(billMonth);
    billAllData.setBillType("DONE");
    billAllData.setLastPayment(CreditResultUtil.StringToBigDecimal("-"+last_payment));
    billAllData.setLastBalance(CreditResultUtil.StringToBigDecimal(last_balance));
    billAllData.setNewBalance(CreditResultUtil.StringToBigDecimal(new_balance));
    billAllData.setMinPayment(CreditResultUtil.StringToBigDecimal(min_payment));
    billAllData.setCreditLimit(CreditResultUtil.StringToBigDecimal(creditLimit));
    billAllData.setNewCharges(CreditResultUtil.StringToBigDecimal(new_charges));
    billAllData.setUsdCreditLimit(new BigDecimal("0.00"));
}

/**
 * 解析已出账单表头数据(美元)
 */
function parseDollarBaseData(doc,billAllData){
    var usdElement = doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1)");
    if (!usdElement.isEmpty()&&usdElement.toString().contains("美元")) {
        logger.info("当前账户的账单具有美元的相关信息");
        var usd_last_balance = doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(2) > span:nth-child(1)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
        var usd_new_charges=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(3)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
        var usd_last_payment=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(4)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
        var usd_new_balance=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(6) > span:nth-child(1)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
        var usd_min_payment=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(7)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
        billAllData.setUsdLastBalance(CreditResultUtil.StringToBigDecimal(usd_last_balance));
        billAllData.setUsdNewCharges(CreditResultUtil.StringToBigDecimal(usd_new_charges));
        billAllData.setUsdLastPayment(CreditResultUtil.StringToBigDecimal("-"+usd_last_payment));
        billAllData.setUsdNewBalance(CreditResultUtil.StringToBigDecimal(usd_new_balance));
        billAllData.setUsdMinPayment(CreditResultUtil.StringToBigDecimal(usd_min_payment));
        billAllData.setUsdCreditLimit(new BigDecimal("0.00"))
    }
}

/**
 * 解析已出账单,分期明细
 * @param shoppingList  购物列表
 */
function parseDoneInstallments(doc,handFeeList){

    //存放分期明细
    var installmentList=new LinkedList();

    var elements = doc.select("div.wapper:nth-child(3) > table:nth-child(1) > tbody:nth-child(1)>tr");

    for(var i=1;i<elements.size();i++) {
        var element = elements.get(i);
        var transDate = element.select("td:nth-child(1)").get(0).text();
        var postDate = element.select("td:nth-child(2)").get(0).text();
        var description = element.select("td:nth-child(3)").get(0).text();
        var amount_money = element.select("td:nth-child(4)").get(0).text();
        //var cardNum = element.select("td:nth-child(5)").get(0).text();

        if (description.contains("分期") && description.contains("手续费") || description.contains("本金")) {
            //1.确定全部为分期的内容(不含本金转回或者差额等)，将其存放到本金一个集合  手续费一个集合
            //2.使用排序将其按照金额大小将手续费排序
            //3.分别对应手续费和本金放到一个对象中，放入BillAllDate对象中
            if (description.contains("手续费")) {
                var installment = new Installment();
                installment.setTransferfeeDesc("");
                var handFee = amount_money.substring(0, amount_money.length - 1);
                installment.setHandingFee(CreditResultUtil.StringToBigDecimal(handFee));
                installment.setHandingfeeDesc(description);
                //添加分期手续费
                handFeeList.add(installment);
            }

            if (description.contains("本金") && !description.contains("转回")) {
                var installment = new Installment();
                installment.setTransferfeeDesc("");
                installment.setShoppingsheetId(UUID.randomUUID().toString());
                installment.setBillId(null);
                installment.setTransferFee(null);
                installment.setCurrencyType("CNY");
                installment.setInstallmentDesc(description);
                installment.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(transDate + " 00:00:00"));
                installment.setPostDate(yyyy_MM_dd_PARSER.parse(postDate));
                var installmentCount = getInstallmentCount(description);
                installment.setCurrentMonth(installmentCount[0]);
                installment.setTotalMonth(installmentCount[1]);
                installment.setInstallmentType(judgeInstallmentType(description));
                var installmentMoney = amount_money.substring(0, amount_money.length - 1);
                installment.setAmountMoney(CreditResultUtil.StringToBigDecimal(installmentMoney));

                //添加账单明细
                installmentList.add(installment);
            }
        }
    }

    return installmentList;
}


/**
 * 解析已出账单,购物账单明细
 * @param shoppingList  购物列表
 */
function parseDoneShoppingSheets(doc){
    //存放购物明细
    var shoppingSheets=new ArrayList();

    var elements = doc.select("div.wapper:nth-child(3) > table:nth-child(1) > tbody:nth-child(1)>tr");
    var cardNum="";
    for(var i=1;i<elements.size();i++){
        var element = elements.get(i);
        var transDate = element.select("td:nth-child(1)").get(0).text();
        var postDate=element.select("td:nth-child(2)").get(0).text();
        var description=element.select("td:nth-child(3)").get(0).text();
        var amount_money=element.select("td:nth-child(4)").get(0).text();
        //相同卡号可以不用重复解析
        if(cardNum==""){
            cardNum=element.select("td:nth-child(5)").get(0).text();
        }
        //实例购物账单
        var expense=new Expense();
        expense.setNameOnOppositeCard("");
        expense.setOppositeBank("");
        expense.setOppositeCardNo("");
        expense.setRemark("");
        expense.setTransAddr("");
        expense.setTransChannel("");
        expense.setTransMethod("");
        expense.setId(UUID.randomUUID().toString());
        expense.setCardNum(cardNum);
        expense.setBalance(null);//交易明细的balance
        expense.setCurrencyType("CNY");
        expense.setDescription(description);
        expense.setOrderIndex(i);
        expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(transDate+" 00:00:00"));
        expense.setPostDate(yyyy_MM_dd_PARSER.parse(postDate));

        var category=CategoryUtil.getCreditCategory("SHANGHAI", description, amount_money);
        if (category.equals("OTHERFEE")&&description.contains("公司")&&amount_money.contains("+")) {
            category="SHOPPING";//即 当无法匹配时，判断描述包含公司、同时金额为支出的时候 设置字段为SHOPPING
        }
        if (category.equals("INSTALLMENT") && (description.contains("差额")||description.contains("本金转回"))) {
            category="OTHERFEE";//当匹配为分期的时候，同时含有差额 或者本金转回等的时候，将其归类为
        }
        expense.setCategory(category);
        if (amount_money.contains("+")) {//支出
            expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(amount_money.replaceAll("\\+", "")));
        }else if (amount_money.contains("-")){
            expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(amount_money.replaceAll("\\-", "")).divide(new BigDecimal(-1)));
        }

        //添加购物明细
        shoppingSheets.add(expense);
    }
    return shoppingSheets;
}

/**
 *  将分期本金和手续费分别对应起来
 * @param billAllData
 * @param installmentList 分期本金集合
 * @param handFeeList 分期手续费集合
 */
function parseInstallmentAndHandFee(installmentList, handFeeList){
    logger.info("分别对应{}月账单的分期分期手续费",billAllData.getBillMonth());
    bubbleSort(installmentList,"");
    bubbleSort(handFeeList, "handfee");
    if (handFeeList.size()==installmentList.size()) {
        for (var i = 0; i < installmentList.size(); i++) {
            var installment = installmentList.get(i);
            var handFee = handFeeList.get(i);
            installment.setHandingFee(handFee.getHandingFee());//
            installment.setHandingfeeDesc(handFee.getHandingfeeDesc());
        }
    }else{
        logger.info("ABCBank taskkey={}分期手续费与分期对应出错,即分期和本金并不对应，分期的数量为{}，手续费的数量为{}",context.get(LUA_TASK_KEY),installmentList.size(),handFeeList.size());
        for(var i=0;i<installmentList.size();i++){//当现在的本金和 手续费都是按照费用从大到小的顺序排序
            var installment = installmentList.get(i);
            if ((i+1)<=handFeeList.size()) {
                var handFee = handFeeList.get(i);
                installment.setHandingFee(handFee.getHandingFee());
                installment.setHandingfeeDesc(handFee.getHandingfeeDesc());

            }else{
                installment.setHandingFee(null);//如果当前分期对应的手续没有，那么手续费设置为null
                installment.setHandingfeeDesc("");
            }

        }
    }
}

/**
 * 解析已出账单的美元信息
 * @param month
 * @param billAllData
 * @param document
 */
function parseUsdDoneBill(document, billAllData,month){
    logger.info("开始解析美元账单信息");
    try {
        var usdFlag = document.select("div.wapper:nth-child(8) > span:nth-child(1)").get(0).text();
        if (usdFlag.contains("美元账户没有交易记录")) {
            logger.info("当前月{}没有美元相关信息,停止解析美元相关");
            return;
        }
    } catch ( e) {
        statCaughtException(context, e);
        logger.info("解析美元账单信息失败，停止解析");
        return;
    }
    var usdElement = document.select("div.wapper:nth-child(7) > table:nth-child(1) > tbody:nth-child(1) > tr");
    if (!usdElement.isEmpty()) {
        var shopping_sheets = billAllData.getShoppingSheets();
        var order_index=shopping_sheets.size()+1;
        for(var i=0;i<usdElement.size();i++){
            if (i==0) {
                continue;
            }
            var element = usdElement.get(i);
            var transDate = element.select("td:nth-child(1)").get(0).text();
            var postDate=element.select("td:nth-child(2)").get(0).text();
            var description=element.select("td:nth-child(3)").get(0).text();
            var amount_money=element.select("td:nth-child(4)").get(0).text();
            var cardNum=element.select("td:nth-child(5)").get(0).text();
            var expense=new Expense();
            expense.setId(UUID.randomUUID().toString());
            expense.setCardNum(cardNum);
            expense.setCurrencyType("USD");
            expense.setDescription(description);
            expense.setOrderIndex(order_index);
            order_index++;
            expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(transDate+" 00:00:00"));
            expense.setPostDate(yyyy_MM_dd_PARSER.parse(postDate));

            expense.setCategory(CreditResultUtil.judgeBillCategory(description));
            if (description.contains("还款")) {
                var money=amount_money.replaceAll("\\-", "").replaceAll("\\+", "");
                var usd_last_payment = billAllData.getUsdLastPayment();
                if (usd_last_payment==null) {
                    usd_last_payment=new BigDecimal("0");
                    usd_last_payment=usd_last_payment.add(CreditResultUtil.StringToBigDecimal("-"+money));
                }else{
                    usd_last_payment=usd_last_payment.add(CreditResultUtil.StringToBigDecimal("-"+money));
                }
                billAllData.setLastPayment(usd_last_payment);
            }
            if (amount_money.contains("+")) {//支出
                expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(amount_money.replaceAll("\\+", "")));
                var usd_new_charges = billAllData.getUsdNewCharges();
                if (usd_new_charges==null) {
                    usd_new_charges=new BigDecimal("0");
                    usd_new_charges=usd_new_charges.add(expense.getAmountMoney());
                }else{
                    usd_new_charges=usd_new_charges.add(expense.getAmountMoney());
                }
                billAllData.setUsdNewCharges(usd_new_charges);
            }
            shopping_sheets.add(expense);
        };
    }
}